package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"yk1-assistant/caches"
	"yk1-assistant/models"
)

func ListBigCar(c *gin.Context) {
	var list []models.BigOrderList
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "2"))
	offset := (page - 1) * pageSize
	redis_key := "Big_order_List_" + strconv.Itoa(page)
	cacheData, _ := caches.Rdb.Get(caches.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("big_orders").Select(
			"big_orders.id AS OrderId",
			"big_orders.order_code AS OrderCode",
			"big_orders.order_peo AS OrderPeo",
			"big_orders.order_price AS OrderPrice",
			"big_orders.order_status AS OrderStatus",
			"big_car_abbs.car_code AS CarCode",
			"big_car_abbs.car_name AS CarName",
			"big_car_abbs.car_type AS CarType",
			"big_car_abbs.car_mileage AS CarMileage",
		).
			Joins("LEFT JOIN big_car_abbs ON big_car_abbs.id = big_orders.bid").
			Offset(offset).Limit(pageSize).Debug().Find(&list)
		jsonData, _ := json.Marshal(&list)
		caches.Rdb.Set(caches.Ctx, redis_key, jsonData, time.Hour*2)
	}
	models.DB.Table("big_orders").Select(
		"big_orders.id AS OrderId",
		"big_orders.order_code AS OrderCode",
		"big_orders.order_peo AS OrderPeo",
		"big_orders.order_price AS OrderPrice",
		"big_orders.order_status AS OrderStatus",
		"big_car_abbs.car_code AS CarCode",
		"big_car_abbs.car_name AS CarName",
		"big_car_abbs.car_type AS CarType",
		"big_car_abbs.car_mileage AS CarMileage",
	).
		Joins("LEFT JOIN big_car_abbs ON big_car_abbs.id = big_orders.bid").
		Offset(offset).Limit(pageSize).Debug().Find(&list)
	var total int64
	models.DB.Model(&models.BigOrder{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"data":  list,
		"total": total,
	})
	return
}
